﻿using System.Data;
using System.Data.Common;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Xoohoo.Extensions;
using Xoohoo.Models;
using Xoohoo.Models.InputModels;

namespace Xoohoo.Repositories.SqlServerEntLibDAB
{
    public class SiteRepository : RepositoryBase, ISiteRepository
    {
        private readonly Database _db;

        public SiteRepository(string connectionStringName)
        {
            this._db = DatabaseFactory.CreateDatabase(connectionStringName);
        }

        #region ISiteRepository Members

        public Site GetItem()
        {
            string sql = "select top 1 * from Site";
            DbCommand cmd = _db.GetSqlStringCommand(sql);
            IDataReader dr = _db.ExecuteReader(cmd);
            Site site = Project(dr);
            dr.Close();
            return site;
        }

        public bool Save(SiteInput site)
        {
            string sql = @"Update Site Set
                         SiteName=@SiteName
                        ,SiteHost=@SiteHost
                        ,SiteTitle=@SiteTitle
                        ,SiteKeywords=@SiteKeywords
                        ,SiteDescription=@SiteDescription
                        ,Copyright=@Copyright
                        ,FavIconUrl=@FavIconUrl
                        ,PageTitleSeparator=@PageTitleSeparator
                        ,SkinsPath=@SkinsPath
                        ,SkinsScriptsPath=@SkinsScriptsPath
                        ,SkinsStylesPath=@SkinsStylesPath
                        ,AdminPath=@AdminPath";


            DbCommand cmd = _db.GetSqlStringCommand(sql);
            _db.AddInParameter(cmd, "SiteName", DbType.String, site.SiteName);
            _db.AddInParameter(cmd, "SiteHost", DbType.String, site.SiteHost);
            _db.AddInParameter(cmd, "SiteTitle", DbType.String, site.SiteTitle);
            _db.AddInParameter(cmd, "SiteKeywords", DbType.String, site.SiteKeywords);
            _db.AddInParameter(cmd, "SiteDescription", DbType.String, site.SiteDescription);
            _db.AddInParameter(cmd, "Copyright", DbType.String, site.Copyright);
            _db.AddInParameter(cmd, "FavIconUrl", DbType.String, site.FavIconUrl);
            _db.AddInParameter(cmd, "PageTitleSeparator", DbType.String, site.PageTitleSeparator);
            _db.AddInParameter(cmd, "SkinsPath", DbType.String, site.SkinsPath);
            _db.AddInParameter(cmd, "AdminPath", DbType.String, site.AdminPath);

            _db.ExecuteNonQuery(cmd);

            return true;
        }

        #endregion

        #region Private Methods

        private Site Project(IDataReader dr)
        {
            Site site = null;
            if (dr.Read())
            {
                site = dr.ToModel<Site>();
            }
            return site;
        }

        #endregion
        
    }
}
